package com.szq.pattern;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 使用 ThreadLocal 的方式
 * @author: szq
 * @date: 2021-09-02 09:40:16
 */
public class Singleton_08 {

    private static final ThreadLocal<Singleton_08> local = new ThreadLocal<Singleton_08>();
    private Map<String, Object> data = new HashMap<String, Object>();

    /**
     * 批量存数据
     * @param data
     */
    public void setData(Map<String, Object> data) {
        getSingleton().data.putAll(data);
    }

    /**
     * 存数据
     * @param key
     * @param value
     */
    public void set(String key, Object value){
        getSingleton().data.put(key, value);
    }

    /**
     * 取数据
     * @param key
     * @return
     */
    public Object get(String key){
        return getSingleton().data.get(key);
    }

    /**
     * 延迟初始化
     * @return
     */
    public static Singleton_08 getSingleton(){
        Singleton_08 singleton08 = local.get();
        if (null == singleton08){
            singleton08 = init();
        }
        return singleton08;
    }

    /**
     * 初始化
     * @return
     */
    private static Singleton_08 init() {
        Singleton_08 singleton08 = new Singleton_08();
        local.set(singleton08);
        return singleton08;
    }

    /**
     * 删除实例
     */
    public void remove(){
        local.remove();
    }

}
